package com.example.testdemo.sqlite;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.example.testdemo.R;
import com.example.testdemo.home.BaseActivity;

/**
 * Created by yi on 2018/8/2.
 * Android 数据库支持类  SQLiteDatabase 的应用
 */

public class SQLiteCacheActivity extends BaseActivity{
    private EditText pidEt;
    private EditText urlEt;
    private EditText dataEt;

    private String pid;
    private String url;
    private String data;
    private SQLiteCacheHelp help;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sqlite);
        findView();
        help = new SQLiteCacheHelp(this);
//        checkPermission();
    }

    private void findView() {
        pidEt = findViewById(R.id.pidEt);
        urlEt = findViewById(R.id.urlEt);
        dataEt = findViewById(R.id.dataEt);
    }


    private void getEtData() {
        pid = pidEt.getText().toString();
        url = urlEt.getText().toString();
        data = dataEt.getText().toString();
    }
    /**
     * 插入数据
     */
    public void insertData(View view) {
        getEtData();
        help.writable().insert(pid,url,data).commit();
    }
    /**
     * 查数据
     */
    public void queryData(View view) {
        getEtData();
        String data = help.readable().query(pid,url);
        dataEt.setText(data);
    }

    /**
     * 删数据
     */
    public void deleteData(View view) {
        help.writable().clearAll().commit();
    }

    /**
     * 不申请权限貌似也没关系
     */
    @Deprecated
    private void checkPermission() {
        //检查权限（NEED_PERMISSION）是否被授权 PackageManager.PERMISSION_GRANTED表示同意授权
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //用户已经拒绝过一次，再次弹出权限申请对话框需要给用户一个解释
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission
                    .WRITE_EXTERNAL_STORAGE)) {
                Toast.makeText(this, "请开通相关权限，否则无法正常使用本应用！", Toast.LENGTH_SHORT).show();
            }
            //申请权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);

        } else {
            Toast.makeText(this, "授权成功！", Toast.LENGTH_SHORT).show();
        }
    }

}
